package com.suncaper.shop.service;

import com.suncaper.shop.domain.Cart;
import com.suncaper.shop.domain.CartItem;
import com.suncaper.shop.domain.Product;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Service
public class CartService {

    public Cart getCart(HttpSession session) {
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            //将Cart放入当前Session
            session.setAttribute("cart", cart);
        }
        return cart;
    }

    /**
     * 添加到购物车
     *
     * @param count
     * @param product
     * @param session
     * @return
     */
    public Cart addToCart(Integer count, Product product, HttpSession session) {
        //创建购物项
        CartItem cartItem = new CartItem(product, count);
        //获取购物车
        Cart cart = getCart(session);
        cart.addToCart(cartItem);
//        返回数据
        return cart;
    }

    public void addCartView(HttpSession session, Model model, Cart cart, Collection<CartItem> cartItems) {
        model.addAttribute("cart", cart);
        model.addAttribute("items", cartItems);
        session.setAttribute("cart", cart);
        session.setAttribute("items", cartItems);
    }


    public void clearAll(HttpSession session, Cart cart) {
        cart.clearCart();
        session.setAttribute("cart", cart);
    }
}
